package com.kevinwu.zookeepertask.taskone.service;

import com.kevinwu.zookeepertask.taskone.handler.UserServerHandler;
import com.kevinwu.zookeepertask.taskone.utils.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.*;
import org.springframework.stereotype.Service;


@Service
public class UserServiceImpl implements UserService {


    public String sayHello(String word) {
        System.out.println("调用参数： "+word);
        return "调用成功："+word;
    }

    //hostName:ip地址  port:端口号 zkStr zookeeper连接地址
    public static void startServer(String hostName,int port,String zkStr) throws Exception {

        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        //编码
                        pipeline.addLast(new StringEncoder());
                        //解码
                        pipeline.addLast(new RpcDecoder(RpcRequest.class,new JSONSerializer()));
                        pipeline.addLast(new UserServerHandler());
                    }
                });
        serverBootstrap.bind(hostName,port).sync();

        // 使用fluent编程风格
        RetryPolicy exponentialBackoffRetry = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(zkStr)
                .sessionTimeoutMs(50000)
                .connectionTimeoutMs(30000)
                .retryPolicy(exponentialBackoffRetry)
                .namespace("app")  // 独立的命名空间 /zdyrpc
                .build();
        client.start();

        // 创建节点 临时节点 /servers/hostip:port   节点内容为hostip:port
        String path = "/servers/"+hostName+":"+String.valueOf(port);
        String connect = hostName+":"+String.valueOf(port);
        String s = client.create().creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL).forPath(path, connect.getBytes());
        System.out.println("节点递归创建成功，该节点路径" + s);
    }


}
